package TankWar;

import javax.swing.*;
import java.awt.*;

class MyJPanel extends JPanel implements Runnable {

    private boolean running = false;
    private long lastUpdateTime;
    private final int targetFrameRate = 60;
    private final long targetFrameTime = 1000 / targetFrameRate;

    public MyJPanel() {
        setPreferredSize(new Dimension(800, 600));
        setBackground(Color.GRAY);
    }

    public void startGame() {
        running = true;
        lastUpdateTime = System.currentTimeMillis();
        new Thread(this).start();
    }

    public void pauseGame() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastUpdateTime;

            if (elapsedTime >= targetFrameTime) {
                // 更新游戏状态
                updateGame();

                // 重绘游戏画面
                repaint();

                lastUpdateTime = currentTime;
            }

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateGame() {
        try {
            // 在这里添加游戏逻辑的更新，如坦克移动、子弹发射等
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        try {
            //使用双缓冲技术来减少闪烁现象
            Image offScreenBuffer = createImage(getWidth(), getHeight());
            Graphics offScreenGraphics = offScreenBuffer.getGraphics();
            super.paintComponent(offScreenGraphics);
            // 在这里绘制游戏画面，如坦克、子弹、障碍物等
            g.drawImage(offScreenBuffer, 0, 0, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
